//
//  ST_EditOccupationViewController.swift
//  btvideo
//
//  Created by JarvanZhang on 2020/2/3.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import HandyJSON

//职业选择-Controller
class ST_EditOccupationViewController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title_nav_btn.setTitleForAllStates("选择职业")
//        set_up_right_btn()
        
        view.addSubview(root_table_view)
        view.addSubview(children_table_view)
        
        root_table_view.snp.makeConstraints { (make) in
            make.left.bottom.equalToSuperview()
            make.top.equalTo(own_navigation_bar.snp.bottom)
            make.width.equalTo(127)
        }
        
        children_table_view.snp.makeConstraints { (make) in
            make.right.bottom.equalToSuperview()
            make.top.equalTo(own_navigation_bar.snp.bottom)
            make.left.equalTo(root_table_view.snp.right)
        }
        
        
        request_data()
        
    }
    
    
    fileprivate func set_up_right_btn(){
        
        right_nav_btn.setTitleForAllStates("完成")
        right_nav_btn.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.semibold)
        right_nav_btn.backgroundColor = Color.init(hexString: "#FEC207")
        right_nav_btn.cornerRadius = 15
        right_nav_btn.snp.remakeConstraints { (make) in
            make.right.equalTo(own_navigation_bar).offset(-15)
            make.centerY.equalTo(title_nav_btn)
            make.width.equalTo(60)
            make.height.equalTo(30)
        }
        right_nav_btn.isHidden = false
        
    }
    
    fileprivate func request_data(){
        
        JVrequest(PH.FetchOccupationApi, success: { (json) in
            
            if let array = [ST_OccupationModel].deserialize(from: json["data"].rawString()) as? [ST_OccupationModel]{
                
                self.data_array = array
                
                let firstIndex = array.firstIndex { (model) -> Bool in
                    let f = model.detail.contains { (item) -> Bool in
                        return item.id.string == self.info_model.selectedId
                    }
                    return f
                }
                
                if let idx = firstIndex{
                    self.selected_section =  Int(idx.uInt)
                }
                
                self.root_table_view.reloadData()
                
                self.children_table_view.reloadData()
            }
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
        }
        
        
    }
    
//    MARK:- Data
    fileprivate lazy var data_array = [ST_OccupationModel]()
    
    fileprivate var selected_section = 0
    
    var info_model = (selectedId: "" , display_text: "")
    
    var update_value_closure:(((selectedId : String,display_text : String))->())?
    
    
//    MARK: - Properties
    fileprivate let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
    
    fileprivate lazy var root_table_view:UITableView = {
            
        let control = UITableView()
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom , right: 0)
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_EditOccupationRootCell.self)
//        control.register(headerFooterViewClassWith: ST_PairsCenterCornerSectionHeaderView.self)
        control.separatorStyle = .none
        control.backgroundColor = Color.white
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    fileprivate lazy var children_table_view:UITableView = {
                
        let control = UITableView()
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom , right: 0)
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_EditOccupationChildCell.self)
//        control.register(headerFooterViewClassWith: ST_PairsCenterCornerSectionHeaderView.self)
        control.separatorStyle = .none
        control.backgroundColor = Color.init(hexString: "#F2F4F7")
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
}


extension ST_EditOccupationViewController:UITableViewDataSource,UITableViewDelegate{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == root_table_view{
            return data_array.count
        }else{
            return data_array[safe:selected_section]?.detail.count ?? 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if tableView == root_table_view{
        
            let cell = tableView.dequeueReusableCell(withClass: ST_EditOccupationRootCell.self, for: indexPath)
            
            if let name = data_array[safe:indexPath.row]?.name{
                cell.textTitleLabel.text = name
            }
            if indexPath.row == selected_section{
                cell.contentView.backgroundColor = Color.init(hexString: "#F2F4F7")
            }else{
                cell.contentView.backgroundColor = Color.white
            }
            return cell
        }else{
            
            let cell = tableView.dequeueReusableCell(withClass: ST_EditOccupationChildCell.self, for: indexPath)
            
            if let name = data_array[safe:selected_section]?.detail[safe:indexPath.row]?.name{
                cell.textTitleLabel.text = name
            }
            return cell
        }
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if tableView == root_table_view{
            
            selected_section = indexPath.row
            
            root_table_view.reloadData()
            
            children_table_view.reloadData()
        }else{
            
            
            if let item = data_array[safe:selected_section]?.detail[safe:indexPath.row]{
                
                self.update_value_closure?((selectedId : item.id.string,display_text : item.name))
                
            }
            
            goback_previous_controller()
        }
        
    }
    
}


//职业选择项
class ST_OccupationModel: NSObject,HandyJSON {
    
    
    var id = 0
    var pid = 0
    var intro = ""
    var name = ""
    
    var detail = Array<ST_OccupationModel>()
    
    required override init() {
        super.init()
    }
}


//MARK:- Cell
class ST_EditOccupationRootCell:UITableViewCell{
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        contentView.addSubview(textTitleLabel)
        textTitleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(25)
            make.centerY.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var textTitleLabel:UILabel = {
       let control = UILabel()
//        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        control.textColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        return control
    }()
}


class ST_EditOccupationChildCell:UITableViewCell{
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        contentView.addSubview(textTitleLabel)
        textTitleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(30)
            make.centerY.equalToSuperview()
        }
        
        contentView.backgroundColor = Color.init(hexString: "#F2F4F7")
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var textTitleLabel:UILabel = {
       let control = UILabel()
//        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        control.textColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        return control
    }()
}
